package com.hqyj.servlet;

import com.hqyj.model.User;
import com.hqyj.util.DbUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * ClassName  LoginServlet
 * @Author Hjy
 * @Description
 *
 * @Date 2021/12/10 21:25
 * @Version 1.0
 **/
@WebServlet("/login")
public class LoginServlet extends HttpServlet {


    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // doGet方法是服务处理GET请求的方法，
            /*
        1.获取登陆页面的name和password
        2.面向对象（封装思想）
        3.准备Dbutil 复制到Util包下
        4.比较2个user
    */

        //1 获取跳转入参
        String name = req.getParameter("name");
        String password = req.getParameter("password");

        System.out.println(name);
        System.out.println(password);

        //封装对象
        User user = new User(name, password);

        //3.链接数据库，获取数据库里面的正确账号
        Connection connection = DbUtil.getConnection();//获取数据库连接

        //预编译SQL
        PreparedStatement preparedStatement = null;
        try {
            preparedStatement = connection.prepareStatement("SELECT * from user WHERE NAME = ? AND PASSWORD = ? ");
            //插入查询参数
            preparedStatement.setString(1, user.getName());
            preparedStatement.setString(2, user.getPassword());

            //数据库返回的User
            User dbuser = null;
            //执行Sql语句，获取结果集
            ResultSet resultSet = preparedStatement.executeQuery();

            if (resultSet.next()) {//如果查询结果成功，封装数据库返回的user
                String dbname = resultSet.getString("name");
                String dbpassword = resultSet.getString("password");
                Integer id = resultSet.getInt("id");

                dbuser = new User(dbname, dbpassword);
                dbuser.setId(id);

                System.out.println(dbuser.getId());
                System.out.println(dbuser.getName());
                System.out.println(dbuser.getPassword());
                //登陆成功跳转Center.jsp
                req.getRequestDispatcher("jsp/center.jsp").forward(req, resp);

            } else {
                //强制跳转回登陆页面
                req.getRequestDispatcher("jsp/login.jsp").forward(req, resp);

            }


        } catch (SQLException e) {
            e.printStackTrace();
        }

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //doPost方法是服务器处理POST请求的方法

        this.doGet(req, resp);
    }
}
